<?php
/**
 * Validierungsklasse zur Parametervalidierung
 *
 * @author		Joachim Ruf
 * @copyright	Copyright (c) 2003-2013 Loresoft Software (http://www.loresoft.de)
 * @license		http://yapary.loresoft.de/lizenzbedingungen     New BSD License
 *
 * */


/**
 * $val muss einem UTF8-String entsprechen
 * mit vorgegebener Unteren- und/oder Oberen Zeichenlaenge
 * */
Class Yapary_Parameter_CheckStringUtf8 Extends Yapary_Exception_Error Implements Yapary_Parameter_ICheck
{
	private $min, $max;
	function __construct ( $_minLength = NULL, $_maxLength = NULL )
	{
		$this->min = $_minLength;
		$this->max = $_maxLength;
	}


	public function typedef ( $val )
	{
		return (string) $val;
	}


	public function getPattern ()
	{
		return NULL;
	}


	public function isValid ( $val )
	{
		if (!isset($val)) {
			$this->addError(Yapary_Exception_Error::E_UNDEFINED);
			return false;
		}
		if ($this->min != NULL && strlen($val) < $this->min) {
			$this->addError(Yapary_Exception_Error::E_OUT_OF_SIZE);
			return false;
		}
		if ($this->max != NULL && strlen($val) > $this->max) {
			$this->addError(Yapary_Exception_Error::E_OUT_OF_SIZE);
			return false;
		}
		if (!$this->isValidUtf8($val)) {
			//if( @iconv('UTF-8', 'UTF-8//IGNORE', $var) )
			$this->addError(Yapary_Exception_Error::E_WRONG_FORMAT);
			return false;
		}

		return true;
	}
	private function isValidUtf8 ($str)
	{
		$strlen = strlen($str);
		for ($i=0; $i<$strlen; $i++)
		{
			$ord = ord($str[$i]);
			if($ord < 0x80) {
				continue; // 0bbbbbbb
			} elseif (($ord&0xE0)===0xC0 && $ord>0xC1) {
				$n = 1; // 110bbbbb (exkl C0-C1)
			} elseif (($ord&0xF0)===0xE0) {
				$n = 2; // 1110bbbb
			} elseif (($ord&0xF8)===0xF0 && $ord<0xF5) {
				$n = 3; // 11110bbb (exkl F5-FF)
			} else {
				return false;
			}

			for ($o=0; $o<$n; $o++) { // $n Folgebytes? // 10bbbbbb
				if (++$i === $strlen || (ord($str[$i])&0xC0) !== 0x80) {
					return false;
				}
			}
		}

		return true;
	}
}
